package com.jsbs.iam.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jsbs.iam.common.core.aop.LogDb;
import com.jsbs.iam.common.core.dto.Result;
import com.jsbs.iam.common.core.utils.Json;
import com.jsbs.iam.common.core.utils.StringUtils;
import com.jsbs.iam.user.constant.Constants;
import com.jsbs.iam.user.dto.AdminRoleUserDto;
import com.jsbs.iam.user.param.AdminRoleParam;
import com.jsbs.iam.user.service.IamAdminRoleService;
import com.jsbs.iam.user.vo.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * @Author junwc
 * @Date 2022/12/8
 * @Version 1.0
 */
@RestController
@RequestMapping("/iam/user/role")
public class IamAdminRoleController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(IamAdminRoleController.class);

    @Autowired
    private IamAdminRoleService iamAdminRoleService;

    /**
     * 功能描述：管理员角色列表分页查询
     * @return
     */
    @PostMapping("/query")
    @LogDb
    public Result queryAdminRoleList(HttpServletRequest request, @RequestBody AdminRoleParam adminRoleParam) {
        logger.info("Route==>IamAdminRoleController method=queryAdminRoleList 查询管理员角色列表，入参：{}", Json.toJsonString(adminRoleParam));
        try {
            // 获取当前登录人归属租户
            String companyCode = request.getHeader(Constants.COMPANY_CODE);
            if (StringUtils.isEmpty(companyCode)) {
                return Result.failWithMsg("归属租户为空");
            }
            adminRoleParam.setCompanyCode(companyCode);
            // 初始化分页参数
            adminRoleParam.initPage();
            return Result.success(iamAdminRoleService.queryForPage(adminRoleParam));
        } catch (Exception e) {
            logger.error("Route==>IamMenuController method=queryAdminRoleList 查询管理员角色列表异常：{}，入参：{}", e, Json.toJsonString(adminRoleParam));
            return handleException(e);
        }
    }

    /**
     * 功能描述：管理员角色新增/编辑保存
     * @return
     */
    @PostMapping("/save")
    @LogDb
    public Result adminRoleEdit(HttpServletRequest request, @RequestBody AdminRoleInfoVo adminRoleInfoVo) {
        logger.info("Route==>IamAdminRoleController method=adminRoleEdit 管理员角色保存入参：{}", Json.toJsonString(adminRoleInfoVo));
        try {
            // 获取当前登录人
            String userName = request.getHeader(Constants.NAME);
            if (StringUtils.isEmpty(userName)) {
                return Result.failWithMsg("当前登录状态异常");
            }
            // 归属租户
            String companyCode = request.getHeader(Constants.COMPANY_CODE);
            if (StringUtils.isEmpty(companyCode)) {
                return Result.failWithMsg("当前登录归属租户为空");
            }
            adminRoleInfoVo.setCompanyCode(companyCode);
            // 保存管理员角色
            return iamAdminRoleService.saveAdminRole(adminRoleInfoVo, userName);
        } catch (Exception e) {
            logger.error("Route==>IamMenuController method=queryAdminRoleList 管理员角色保存异常，入参：{}，异常：{}", Json.toJsonString(adminRoleInfoVo), e);
            return handleException(e);
        }
    }

    /**
     * 功能描述：管理员角色启用/禁用
     * @return
     */
    @PostMapping("/editstatus")
    @LogDb
    public Result adminRoleStatusEdit(HttpServletRequest httpServletRequest, @RequestBody AdminRoleStatusVo adminRoleStatusVo) {
        logger.info("Route==>IamAdminRoleController method=adminRoleStatusEdit 管理员角色启用/停用入参：{}", Json.toJsonString(adminRoleStatusVo));
        try {
            String userName = httpServletRequest.getHeader(Constants.NAME);
            if (StringUtils.isEmpty(userName)) {
                return Result.failWithMsg("当前登录状态异常");
            }
            // 启用/禁用管理员角色
            return iamAdminRoleService.adminRoleStatusEdit(adminRoleStatusVo, userName);
        } catch (Exception e) {
            logger.error("Route==>IamMenuController method=adminRoleStatusEdit 管理员角色启用/停用异常，入参：{}，异常：{}", Json.toJsonString(adminRoleStatusVo), e);
            return handleException(e);
        }
    }

    /**
     * 功能描述：管理员角色删除
     * @return
     */
    @PostMapping("/delete")
    @LogDb
    public Result adminRoleDelete(HttpServletRequest httpServletRequest, @RequestBody AdminRoleStatusVo adminRoleStatusVo) {
        logger.info("Route==>IamAdminRoleController method=adminRoleDelete 管理员角色批量删除入参：{}", Json.toJsonString(adminRoleStatusVo));
        try {
            // 当前登录人
            String userName = httpServletRequest.getHeader(Constants.NAME);
            if (StringUtils.isEmpty(userName)) {
                return Result.failWithMsg("当前登录状态异常");
            }
            // 管理员角色批量删除
            return iamAdminRoleService.adminRoleBatchDelete(adminRoleStatusVo, userName);
        } catch (Exception e) {
            logger.error("Route==>IamMenuController method=adminRoleDelete 管理员角色批量删除异常，入参：{}，异常：{}", Json.toJsonString(adminRoleStatusVo), e);
            return handleException(e);
        }
    }

    /**
     * 功能描述：管理员角色批量绑定/解绑用户
     * @return
     */
    @PostMapping("/userbind")
    @LogDb
    public Result adminRoleUserBind(HttpServletRequest httpServletRequest, @RequestBody AdminRoleUserVo adminRoleUserVo) {
        logger.info("Route==>IamAdminRoleController method=adminRoleDelete 管理员角色批量绑定/解绑用户入参：{}", Json.toJsonString(adminRoleUserVo));
        try {
            // 当前登录人
            String userName = httpServletRequest.getHeader(Constants.NAME);
            if (StringUtils.isEmpty(userName)) {
                return Result.failWithMsg("当前登录状态异常");
            }
            // 管理员角色批量绑定/解绑用户
            return iamAdminRoleService.adminRoleUserBind(adminRoleUserVo, userName);
        } catch (Exception e) {
            logger.error("Route==>IamMenuController method=adminRoleDelete 管理员角色批量绑定/解绑用户异常，入参：{}，异常：{}", Json.toJsonString(adminRoleUserVo), e);
            return handleException(e);
        }
    }

    /**
     * 功能描述：切换管理员角色
     * @return
     */
    /*@PostMapping("/roleExchange")
    @LogDb
    public Result adminRoleExchange(HttpServletRequest request, HttpServletResponse response, @RequestParam String adminRoleCode) {
        logger.info("Route==>IamAdminRoleController method=adminRoleExchange 切换管理员角色开始adminRoleCode:{}", adminRoleCode);
        try {
            // 当前管理员用户角色列表
            List<IdentAdminUserRoleVo> adminRoleList = JSONArray.parseArray(JSON.toJSONString(Collections.singletonList(request.getHeader(Constants.ADMIN_ROLE_LIST))), IdentAdminUserRoleVo.class);
            // 当前管理员角色编码
            String adminRole = request.getHeader(Constants.ADMIN_ROLE_CODE);
            if (StringUtils.isEmpty(adminRole)) {
                return Result.failWithMsg("当前登录状态异常");
            }
            if (CollectionUtils.isEmpty(adminRoleList)) {
                return Result.failWithMsg("管理员角色列表为空");
            }
            // 切换角色
            if (!adminRoleList.contains(adminRoleCode)) {
                return Result.failWithMsg("管理员角色异常");
            }
            response.setHeader(Constants.ADMIN_ROLE_CODE, adminRoleCode);
            return Result.success();
        } catch (Exception e) {
            logger.error("Route==>IamMenuController method=adminRoleExchange 切换管理员角色异常：", e);
            return handleException(e);
        }
    }*/

    @PostMapping("/queryAdminRoleByUser")
    @LogDb
    public Result<List<AdminUserRoleVo>> queryAdminRoleByUser (@RequestBody AdminRoleUserDto roleUserDto) {
        List<AdminUserRoleVo> adminRoleByUser = iamAdminRoleService.getAdminRoleByUser(roleUserDto.getAccount());
        return Result.success(adminRoleByUser);
    }
}
